import { useState, useRef, useEffect } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import SliderVerification from "./ui/SliderVerification";
import QRCodeLogin from "./QRCodeLogin";
import {
  emailLoginRequest,
  sendEmailCodeRequest,
} from "../services/login/emailLogin";
import alertService from "../utils/alertService";
import userService from "../utils/userService";

interface LoginProps {
  isOpen: boolean;
  onClose: () => void;
  onLogin: (email: string, code: string) => void;
}

// 定义表单验证规则
const schema = yup.object().shape({
  email: yup
    .string()
    .required("邮箱地址不能为空")
    .email("请输入有效的邮箱地址")
    .matches(
      /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/,
      "邮箱格式不正确或顶级域名无效"
    )
    .test(
      "no-consecutive-dots",
      "邮箱中不能包含连续的点",
      (value) => !value || !value.includes("..")
    )
    .test("valid-domain", "邮箱域名无效，请检查拼写", (value) => {
      if (!value) return true;

      // 常见有效域名列表
      const commonDomains = [
        ".com",
        ".net",
        ".org",
        ".edu",
        ".gov",
        ".mil",
        ".cn",
        ".co.jp",
        ".co.uk",
        ".de",
        ".fr",
        ".ca",
        ".ru",
        ".au",
        ".us",
      ];

      // 检查是否是常见有效域名
      let isValidDomain = false;
      for (const domain of commonDomains) {
        if (value.toLowerCase().endsWith(domain)) {
          isValidDomain = true;
          break;
        }
      }

      // 特殊检查QQ邮箱
      if (
        value.toLowerCase().includes("@qq.") &&
        !value.toLowerCase().endsWith("@qq.com")
      ) {
        return false;
      }

      return isValidDomain;
    }),
  verificationCode: yup
    .string()
    .required("验证码不能为空")
    .matches(/^[0-9]{6}$/, "验证码必须是6位数字"),
});

type FormData = yup.InferType<typeof schema>;

const useMediaQuery = (query: string) => {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => {
      setMatches(media.matches);
    };
    media.addEventListener("change", listener);
    return () => media.removeEventListener("change", listener);
  }, [matches, query]);

  return matches;
};

const Login = ({ isOpen, onClose, onLogin }: LoginProps) => {
  const [countdown, setCountdown] = useState(0);
  const [isSending, setIsSending] = useState(false);
  const [sliderVerified, setSliderVerified] = useState(false);
  const [activeTab, setActiveTab] = useState<"email" | "qrcode">("email");
  const modalRef = useRef<HTMLDivElement>(null);
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const isMobile = useMediaQuery("(max-width: 640px)");
  const [qrCodeVisible, setQrCodeVisible] = useState(true);

  // 初始化表单
  const {
    register,
    handleSubmit,
    formState: { errors, isValid, isDirty },
    getValues,
    watch,
    trigger,
  } = useForm<FormData>({
    resolver: yupResolver(schema),
    mode: "onChange", // 在输入变化时进行验证
  });

  // 处理刷新二维码
  const handleRefreshQRCode = () => {
    // 这里可以调用API获取新的二维码
    console.log("刷新二维码");
    // 模拟获取新的二维码
    // 实际应用中这里应该调用后端API获取新的二维码URL
    setTimeout(() => {
      // 假设获取了新的二维码URL
      console.log("二维码已刷新");
    }, 500);
  };

  // 监听邮箱变化以重置验证状态
  const email = watch("email");
  useEffect(() => {
    setSliderVerified(false);
  }, [email]);

  // 处理点击外部关闭
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        modalRef.current &&
        !modalRef.current.contains(event.target as Node)
      ) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
    }

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isOpen, onClose]);

  // 处理ESC键关闭
  useEffect(() => {
    const handleEscapeKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener("keydown", handleEscapeKey);
    }

    return () => {
      document.removeEventListener("keydown", handleEscapeKey);
    };
  }, [isOpen, onClose]);

  // 倒计时处理
  useEffect(() => {
    if (countdown > 0) {
      timerRef.current = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
    } else if (countdown === 0) {
      setIsSending(false);
    }

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, [countdown]);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current);
      }
    };
  }, []);

  // 监听isOpen变化，控制QRCodeLogin的可见性
  useEffect(() => {
    if (isOpen) {
      // 当Login组件显示时，设置QRCode可见
      setQrCodeVisible(true);
    } else if (!isOpen) {
      // 当Login组件要隐藏时，先隐藏QRCode以触发其清理逻辑
      setQrCodeVisible(false);

      // 给QRCode一些时间清理定时器
      const timer = setTimeout(() => {
        // 这里不需要做什么，只是给QRCode组件时间执行清理
      }, 100);

      return () => clearTimeout(timer);
    }
  }, [isOpen]);

  // 表单提交处理
  const onSubmitForm = async (data: FormData) => {
    if (!sliderVerified) {
      // 添加错误提示或者自动滚动到验证区域
      const captchaElem = document.getElementById("captcha-verification");
      if (captchaElem) {
        captchaElem.scrollIntoView({ behavior: "smooth" });
      }
      return;
    }

    try {
      // 检查一下登录前的状态
      console.log("登录前状态:", {
        isLoggedIn: userService.isLoggedIn,
        token: userService.token?.substring(0, 20) + "...",
      });

      const result = await emailLoginRequest({
        email: data.email,
        code: data.verificationCode,
      });

      if (result.code === 200) {
        // 登录成功，用户信息和token已在emailLoginRequest中设置
        console.log("登录成功，准备关闭登录窗口");

        // 调用父组件传递的onLogin回调
        onLogin(data.email, data.verificationCode);
      } else {
        alertService.error(result.message);
      }
    } catch (error) {
      console.error("登录请求失败:", error);
      alertService.error("登录失败，请稍后重试");
    }
  };

  // 处理滑块验证
  const handleSliderVerify = (verified: boolean) => {
    setSliderVerified(verified);
  };

  // 发送验证码
  const handleSendVerificationCode = async () => {
    // 验证邮箱
    const isEmailValid = await trigger("email");
    if (!isEmailValid) return;

    // 验证滑块
    if (!sliderVerified) {
      const captchaElem = document.getElementById("captcha-verification");
      if (captchaElem) {
        captchaElem.scrollIntoView({ behavior: "smooth" });
      }
      return;
    }

    // 如果已经在发送中，不能重复发送
    if (isSending) return;

    // 设置状态为发送中
    setIsSending(true);
    // 设置倒计时（60秒）
    setCountdown(60);

    try {
      // 这里添加发送验证码的API调用
      const result = await sendEmailCodeRequest(getValues("email"));
      if (result.code === 200) {
        alertService.success(`验证码已发送至${getValues("email")}`);
      } else {
        alertService.error(result.message);
      }
    } catch (error) {
      console.error("发送验证码失败:", error);
      // 重置发送状态
      setIsSending(false);
      setCountdown(0);
      alertService.error("发送验证码失败，请稍后再试");
    }
  };

  // 计算登录按钮是否应该禁用
  const isLoginButtonDisabled = () => {
    // 如果表单未验证通过或拼图未验证完成，禁用按钮
    return (
      !isValid || !sliderVerified || !isDirty || Object.keys(errors).length > 0
    );
  };

  // 获取错误提示文本
  const getErrorMessage = () => {
    if (errors.email) return errors.email.message;
    if (!sliderVerified) return "请完成滑块验证";
    if (errors.verificationCode) return errors.verificationCode.message;
    return "";
  };

  // 提前处理不可见状态，确保子组件有机会执行清理逻辑
  if (!isOpen) {
    return (
      <div style={{ display: "none" }}>
        {activeTab === "qrcode" && (
          <QRCodeLogin isOpen={false} onRefresh={handleRefreshQRCode} />
        )}
      </div>
    );
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-md transition-all duration-300 ease-in-out">
      <div
        ref={modalRef}
        className="w-full max-w-md bg-white dark:bg-gray-800 rounded-2xl shadow-[0_0_60px_rgba(0,0,0,0.15)] dark:shadow-[0_0_60px_rgba(0,0,0,0.3)] overflow-hidden transform transition-all duration-300 ease-out scale-100 opacity-100 mx-4"
      >
        <div className="relative">
          {/* 切换标签 */}
          <div className="flex border-b border-gray-200 dark:border-gray-700">
            <div
              className={`flex-1 text-center cursor-pointer py-4 transition-all ${
                activeTab === "email"
                  ? "text-[#1296db] border-b-2 border-[#1296db] font-medium"
                  : "text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
              }`}
              onClick={() => setActiveTab("email")}
            >
              邮箱登录
            </div>
            <div
              className={`flex-1 text-center cursor-pointer py-4 transition-all ${
                activeTab === "qrcode"
                  ? "text-[#1296db] border-b-2 border-[#1296db] font-medium"
                  : "text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
              }`}
              onClick={() => setActiveTab("qrcode")}
            >
              扫码登录
            </div>
          </div>

          {/* 关闭按钮 */}
          <button
            onClick={onClose}
            className="absolute right-4 top-3 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 focus:outline-none transition-colors duration-200"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-6 w-6"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>

          {/* 内容区域 */}
          <div className={`${isMobile ? "px-4" : "px-8"} py-6`}>
            {activeTab === "email" ? (
              <>
                {/* 欢迎信息 */}
                <p className="text-gray-600 dark:text-gray-300 mb-6">
                  请输入您的邮箱并完成滑块验证后获取验证码
                </p>

                {/* 登录表单 */}
                <form
                  onSubmit={handleSubmit(onSubmitForm)}
                  className="space-y-6 w-full"
                >
                  {/* 邮箱输入框 */}
                  <div>
                    <label
                      htmlFor="email"
                      className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      邮箱地址
                    </label>
                    <div className="relative">
                      <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          className="h-5 w-5 text-gray-400"
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={1.5}
                            d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207"
                          />
                        </svg>
                      </div>
                      <input
                        id="email"
                        type="email"
                        {...register("email")}
                        className={`w-full pl-10 pr-4 py-3 border ${
                          errors.email
                            ? "border-red-500 focus:ring-red-500 focus:border-red-500 dark:border-red-400 dark:focus:ring-red-400 dark:focus:border-red-400"
                            : "border-gray-200 dark:border-gray-700 focus:ring-[#1296db]/30 focus:border-[#1296db] dark:focus:ring-blue-500/30 dark:focus:border-blue-500"
                        } rounded-xl bg-white dark:bg-gray-700/50 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 transition-all duration-200 ease-in-out`}
                        placeholder="your@email.com"
                      />
                    </div>
                    {errors.email && (
                      <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                        {errors.email.message}
                      </p>
                    )}
                  </div>

                  {/* 滑块验证 */}
                  <div>
                    <label
                      htmlFor="captcha-verification"
                      id="captcha-verification"
                      className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      滑块验证
                      {sliderVerified && (
                        <span className="ml-2 text-green-500 text-xs">
                          ✓ 已验证
                        </span>
                      )}
                    </label>
                    <SliderVerification
                      onVerify={handleSliderVerify}
                      verified={sliderVerified}
                    />
                  </div>

                  {/* 验证码输入框 */}
                  <div>
                    <label
                      htmlFor="verificationCode"
                      className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2"
                    >
                      验证码
                    </label>
                    <div className="relative flex items-center">
                      <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          className="h-5 w-5 text-gray-400"
                          fill="none"
                          viewBox="0 0 24 24"
                          stroke="currentColor"
                        >
                          <path
                            strokeLinecap="round"
                            strokeLinejoin="round"
                            strokeWidth={1.5}
                            d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"
                          />
                        </svg>
                      </div>
                      <input
                        id="verificationCode"
                        type="text"
                        {...register("verificationCode")}
                        className={`w-full pl-10 pr-4 py-3 border ${
                          errors.verificationCode
                            ? "border-red-500 focus:ring-red-500 focus:border-red-500 dark:border-red-400 dark:focus:ring-red-400 dark:focus:border-red-400"
                            : "border-gray-200 dark:border-gray-700 focus:ring-[#1296db]/30 focus:border-[#1296db] dark:focus:ring-blue-500/30 dark:focus:border-blue-500"
                        } rounded-xl bg-white dark:bg-gray-700/50 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 focus:ring-2 transition-all duration-200 ease-in-out`}
                        placeholder="请输入验证码"
                        maxLength={6}
                      />
                      <button
                        type="button"
                        onClick={handleSendVerificationCode}
                        disabled={
                          isSending || !sliderVerified || !!errors.email
                        }
                        className={`absolute right-2 px-3 py-1.5 rounded-lg text-sm font-medium transition-all duration-200 ease-in-out ${
                          !sliderVerified || isSending || !!errors.email
                            ? "bg-gray-100 text-gray-400 dark:bg-gray-700 dark:text-gray-500 cursor-not-allowed"
                            : "bg-green-100 text-green-600 hover:bg-green-200 dark:bg-green-900/20 dark:text-green-400 dark:hover:bg-green-900/30"
                        }`}
                        aria-label={isSending ? "请稍等" : "发送验证码"}
                      >
                        {isSending ? `${countdown}秒后重试` : "发送验证码"}
                      </button>
                    </div>
                    {errors.verificationCode && (
                      <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                        {errors.verificationCode.message}
                      </p>
                    )}
                    {!sliderVerified && !errors.verificationCode && (
                      <p className="mt-1 text-sm text-red-600 dark:text-red-400">
                        请先完成上方滑块验证
                      </p>
                    )}
                  </div>

                  {/* 登录按钮 */}
                  <div className="mt-2">
                    <button
                      type="submit"
                      disabled={isLoginButtonDisabled()}
                      className={`w-full flex justify-center py-3 px-4 border border-transparent rounded-xl shadow-sm text-sm font-medium text-white transition-all duration-200 ease-in-out hover:translate-y-[-1px] hover:shadow-md active:translate-y-[1px] ${
                        isLoginButtonDisabled()
                          ? "bg-gray-400 cursor-not-allowed"
                          : "bg-gradient-to-r from-[#1296db] to-[#0d85c7] hover:from-[#0d85c7] hover:to-[#0b77b3] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#1296db] dark:focus:ring-offset-gray-800"
                      }`}
                    >
                      登录
                    </button>
                    {isLoginButtonDisabled() && getErrorMessage() && (
                      <p className="mt-1 text-sm text-center text-red-600 dark:text-red-400">
                        {getErrorMessage()}
                      </p>
                    )}
                  </div>
                </form>
              </>
            ) : (
              <QRCodeLogin
                onRefresh={handleRefreshQRCode}
                isOpen={qrCodeVisible && isOpen}
              />
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
